package com.ruyuan.user.server.rpc;

import com.ruyuan.common.model.PageDTO;
import com.ruyuan.common.model.Response;
import com.ruyuan.user.api.AuthorityReadFacade;
import com.ruyuan.user.api.model.request.CheckUserAuthorityRequest;
import com.ruyuan.user.api.model.response.AuthorityDTO;
import com.ruyuan.user.server.domain.model.AuthResource;
import com.ruyuan.user.server.domain.model.Authority;
import com.ruyuan.user.server.domain.service.AuthorityDomainService;
import com.ruyuan.user.server.domain.service.RoleDomainService;
import com.ruyuan.user.server.domain.service.request.PageQueryAuthResourceReq;
import com.ruyuan.user.server.domain.service.request.QueryUserAuthoritiesParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xx
 */
@Service
public class AuthorityReadFacadeImpl implements AuthorityReadFacade {

    @Autowired
    private RoleDomainService roleDomainService;

    @Autowired
    private AuthorityDomainService authorityDomainService;

    @Override
    public Response<List<AuthorityDTO>> checkUserAuthority(CheckUserAuthorityRequest request) {
        // 先根据code查出资源ID
        PageQueryAuthResourceReq pageQueryAuthResourceRequest = new PageQueryAuthResourceReq();
        pageQueryAuthResourceRequest.setOrgId(request.getRootOrgId());
        pageQueryAuthResourceRequest.setAuthResourceCode(request.getAuthResourceCode());
        pageQueryAuthResourceRequest.setCurrent(1);
        pageQueryAuthResourceRequest.setPageSize(Integer.MAX_VALUE);
        PageDTO<AuthResource> authResourcePage = authorityDomainService.queryAuthResourceByCondition(pageQueryAuthResourceRequest);
        List<AuthResource> authResources = authResourcePage.getData();
        if (CollectionUtils.isEmpty(authResources)) {
            return Response.success(new ArrayList<>());
        }
        // 再根据userId+资源ID查询所有权限
        QueryUserAuthoritiesParam queryUserAuthoritiesParam = new QueryUserAuthoritiesParam();
        queryUserAuthoritiesParam.setUserId(request.getUserId());
        queryUserAuthoritiesParam.setAuthResourceId(authResources.get(0).getId());
        List<Authority> userAllAuthorities = roleDomainService.queryUserAllAuthorities(queryUserAuthoritiesParam);
        List<AuthorityDTO> authorityDTOList = userAllAuthorities.stream().map(authority -> {
            AuthorityDTO authorityDTO = new AuthorityDTO();
            BeanUtils.copyProperties(authority, authorityDTO);
            return authorityDTO;
        }).collect(Collectors.toList());
        return Response.success(authorityDTOList);
    }
}
